package com.ruoyi.match.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.match.config.MyMapConvConvertStrategy;
import com.ruoyi.match.domain.RyAddr;
import com.ruoyi.match.service.IRyAddrService;
import org.apache.poi.ss.formula.functions.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.match.domain.ChOrder;
import com.ruoyi.match.service.IChOrderService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author ruoyi
 * @date 2023-12-12
 */
@RestController
@RequestMapping("/order")
public class  ChOrderController extends BaseController
{
    @Autowired
    private IChOrderService chOrderService;
    @Autowired
    private IRyAddrService ryAddrService;
    @Autowired
    MyMapConvConvertStrategy myMapConvConvertStrategyl;

    /**
     * 查询订单列表
     */
    @RequiresPermissions("match:order:list")
    @GetMapping("/list")
    public TableDataInfo list(ChOrder chOrder)
    {
        startPage();
        List<ChOrder> list = chOrderService.selectChOrderList(chOrder);
        //List<ChOrder> list = chOrderService.selectChOrderListShow(chOrder);
        return getDataTable(list);
    }
    @GetMapping("/tree")
    public List<Tree<String>> treelist()
    {
        List<RyAddr> list = ryAddrService.selectListShow();
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getPid()+"");
                    // 扩展属性 ...
                    tree.putExtra("cdname", treeNode.getAddrName());
                });
        return treeNodes;
    }

    /**
     * 导出订单列表
     */
    @RequiresPermissions("match:order:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ChOrder chOrder) throws IOException {
        List<ChOrder> list = chOrderService.selectChOrderList(chOrder);
        EasyExcel.write(response.getOutputStream(),ChOrder.class)
                .registerConverter(myMapConvConvertStrategyl)
                .sheet("用户订单")
                .doWrite(list);

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("Excel", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //写出的流
            ServletOutputStream outputStream = response.getOutputStream();
            //构建对象
            ExcelWriter excelWriter = EasyExcel.write(outputStream, ChOrder.class).build();
            Page<ChOrder> page = PageHelper.startPage(1, 3);
            PageInfo<ChOrder> info = new PageInfo<>(page, 3);
            WriteSheet sheet0 = EasyExcel.writerSheet(0, "Sheet" + 0).build();
            excelWriter.write(info.getList(),sheet0);
            Page<ChOrder> page2 = PageHelper.startPage(2, 3);
            PageInfo<ChOrder> info1 = new PageInfo<>(page2, 3);
            WriteSheet sheet1 = EasyExcel.writerSheet(1, "Sheet" + 1).build();
            excelWriter.write(info1.getList(),sheet1);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            //换成hutool里的方法
            response.getWriter().println(JSONUtil.toJsonStr(map));
        }

    }
    /**
     * 获取订单详细信息
     */
    @RequiresPermissions("match:order:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(chOrderService.selectChOrderById(id));
    }

    /**
     * 新增订单
     */
    @RequiresPermissions("match:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ChOrder chOrder)
    {
        return toAjax(chOrderService.insertChOrder(chOrder));
    }

    /**
     * 修改订单
     */
    @RequiresPermissions("match:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ChOrder chOrder)
    {
        return toAjax(chOrderService.updateChOrder(chOrder));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("match:order:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(chOrderService.deleteChOrderByIds(ids));
    }
}
